// 服务器统计服务
export interface PageData {
  path: string
  title: string
}

export interface ServerStats {
  stats: {
    totalVisits: number
    todayVisits: number
    weekVisits: number
    monthVisits: number
  }
  popularPages: Array<{ path: string; title: string; views: number }>
  lastUpdated: string
}

export class ServerAnalyticsService {
  private static instance: ServerAnalyticsService
  private retryQueue: Array<{ pageData: PageData; version?: string }> = []
  private isOnline = true

  private constructor() {
    this.startHealthCheck()
  }

  static getInstance(): ServerAnalyticsService {
    if (!ServerAnalyticsService.instance) {
      ServerAnalyticsService.instance = new ServerAnalyticsService()
    }
    return ServerAnalyticsService.instance
  }

  // 检查服务器连接
  private async checkServerHealth(): Promise<boolean> {
    try {
      const response = await fetch(`/api/health`)
      const result = await response.json()
      return result.success
    } catch (error) {
      console.warn('统计服务器连接失败:', error)
      return false
    }
  }

  // 开始健康检查
  private startHealthCheck(): void {
    if (typeof window !== "undefined") {
      setInterval(async () => {
        const wasOnline = this.isOnline
        this.isOnline = await this.checkServerHealth()
        
        if (!wasOnline && this.isOnline) {
          console.log('📊 统计服务器已连接')
          this.processRetryQueue()
        } else if (wasOnline && !this.isOnline) {
          console.warn('📊 统计服务器连接断开')
        }
      }, 30000) // 每30秒检查一次
    }
  }

  // 处理重试队列
  private async processRetryQueue(): Promise<void> {
    if (this.retryQueue.length === 0) return
    
    console.log(`📊 处理 ${this.retryQueue.length} 个待发送页面访问`)
    
    try {
      const queueItems = [...this.retryQueue]
      this.retryQueue = []
      
      for (const item of queueItems) {
        await this.sendPageView(item.pageData, item.version)
      }
    } catch (error) {
      console.error('处理重试队列失败:', error)
      // 重新加入队列
      this.retryQueue.unshift(...this.retryQueue)
    }
  }

  // 发送页面访问
  private async sendPageView(pageData: PageData, version?: string): Promise<boolean> {
    try {
      const response = await fetch(`/api/pageview`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ pageData, version })
      })
      
      const result = await response.json()
      return result.success
    } catch (error) {
      console.error('发送页面访问失败:', error)
      return false
    }
  }

  // 跟踪页面访问
  async trackPageView(pageTitle?: string, version?: string): Promise<void> {
    // 获取当前页面路径，移除版本前缀
    let path = window.location.pathname
    
    // 移除版本前缀（如 /v13.0/）
    const versionMatch = path.match(/^\/v\d+\.\d+\//)
    if (versionMatch) {
      path = path.replace(versionMatch[0], '/')
    }
    
    // 移除语言前缀（如 /en_us/）
    const langMatch = path.match(/^\/(en_us|zh_cn)\//)
    if (langMatch) {
      path = path.replace(langMatch[0], '/')
    }
    
    // 确保路径以 / 开头
    if (!path.startsWith('/')) {
      path = '/' + path
    }
    
    // 移除末尾的 .html 或 /
    path = path.replace(/\.html$/, '').replace(/\/$/, '')
    
    // 检查是否为404页面
    const is404Page = this.is404Page(path, pageTitle || document.title)
    if (is404Page) {
      console.log('🚫 跳过404页面访问记录:', path)
      return
    }
    
    const pageData: PageData = {
      path: path,
      title: pageTitle || document.title
    }

    console.log('📊 记录页面访问:', pageData, '版本:', version)
    await this.sendPageViewToServer(pageData, version)
  }

  // 检查是否为404页面
  private is404Page(path: string, title: string): boolean {
    // 检查页面标题是否包含404相关关键词
    const title404Keywords = ['404', 'not found', '页面未找到', '页面不存在']
    const has404Title = title404Keywords.some(keyword => 
      title.toLowerCase().includes(keyword.toLowerCase())
    )
    
    // 检查路径是否为特定的404页面路径（精确匹配）
    const errorPaths = ['/404', '/not-found', '/404.html']
    const isErrorPath = errorPaths.some(errorPath => 
      path.toLowerCase() === errorPath.toLowerCase()
    )
    
    // 检查路径是否以 /404 开头（404页面）
    const is404Path = path.toLowerCase().startsWith('/404')
    
    return has404Title || isErrorPath || is404Path
  }

  // 发送页面访问到服务器
  private async sendPageViewToServer(pageData: PageData, version?: string): Promise<void> {
    if (this.isOnline) {
      const success = await this.sendPageView(pageData, version)
      if (!success) {
        this.retryQueue.push({ pageData, version })
      }
    } else {
      this.retryQueue.push({ pageData, version })
    }
  }

  // 获取统计数据
  async getStats(version?: string): Promise<ServerStats | null> {
    try {
      const url = version 
        ? `/api/stats?version=${encodeURIComponent(version)}`
        : `/api/stats`
      const response = await fetch(url)
      const result = await response.json()
      
      if (result.success) {
        return result.data
      }
      return null
    } catch (error) {
      console.error('获取统计数据失败:', error)
      return null
    }
  }

  // 获取原始数据
  async getRawData(): Promise<any> {
    try {
      const response = await fetch(`/api/data`)
      const result = await response.json()
      
      if (result.success) {
        return result.data
      }
      return null
    } catch (error) {
      console.error('获取原始数据失败:', error)
      return null
    }
  }

  // 清除所有数据
  async clearData(version?: string): Promise<boolean> {
    try {
      const url = version 
        ? `/api/data?version=${encodeURIComponent(version)}`
        : `/api/data`
      const response = await fetch(url, {
        method: 'DELETE'
      })
      const result = await response.json()
      return result.success
    } catch (error) {
      console.error('清除数据失败:', error)
      return false
    }
  }

  // 检查连接状态
  isServerOnline(): boolean {
    return this.isOnline
  }

  // 获取重试队列长度
  getRetryQueueLength(): number {
    return this.retryQueue.length
  }
}

// 导出单例实例
export const serverAnalyticsService = ServerAnalyticsService.getInstance() 